#include "list.h"
#include <stdlib.h>

int get_size(list *l) {
	int size = 0;
	list_element *cursor;
	for_each_list_entry(cursor, l) {
		size++;
	}
	return size;
}

list_element* addObject(list *l, void *object) {
	add_object(l, object);
}

list_element* add_object(list *l, void *object) {
	list_element *cursor = l->head;
	
	if(cursor == NULL) {
		verbose1("cursor null\n");
		l->head = (list_element*)malloc(sizeof(list_element));
		cursor = l->head;
	}
	else {
		verbose1("cursor else\n");
		while(cursor->next != NULL) {	verbose1("cursor next\n");
			cursor = cursor->next;
		}
		cursor->next = (list_element*)malloc(sizeof(list_element));
		cursor = cursor->next;
	}
	
	cursor->object = object;
	cursor->next = NULL;
	
	return cursor;
}


list_element* getElement(list *l, int n) {
	list_element *cursor;
	int i;
	for(
			cursor = l->head, i = 0;
			(cursor != NULL) && (i < n);
			cursor = cursor->next, i++
			)	{}
	
	return cursor;
}

list_element* get_next_element(list *l) {
	static list_element *c;
	
	if(l!=NULL)
		c = l->head;
	else if (c!=NULL)
		c = c->next;
	return c;
}

void* get_next_object(list *l) {
	list_element *e;
	e = get_next_element(l);
	if(e!=NULL)
		return e->object;
		
	return NULL;
}
void* getObject(list *l, int n) {
	list_element *e = getElement(l, n);
	if(e!=NULL)
		return e->object;
	else
		return NULL;
}


list_element* searchElement(list *l, void *object) {
	list_element *cursor = l->head;
	
	while(cursor != NULL) {
		if(cursor->object == object) {
			return cursor;
		}
		cursor = cursor->next;
	}
	
	return NULL;
}

void delete_object(list *l, void *object){
	list_element* cursor = l->head;
	list_element* previous = NULL;

	while(cursor != NULL){
		if(cursor->object == object){
			if(previous==NULL){
				l->head = cursor->next;
			}else{
				previous->next = cursor->next;
			}
			cursor->next = NULL;
			cursor->object= NULL;
			return;
		}
		previous = cursor;
		cursor = cursor->next;
	}
}
